<template>
  <div>
    <div id="amapcontainer" style="height: 500px"></div>
    <!-- 搜索框 -->
    <div class="search">
      <div style="display: flex">
        <el-input
          id="search-input"
          placeholder="请输入关键字"
          v-model="searchAddress"
          class="input-with-select"
          style="height: 40px"
        >
        </el-input>
        <button
          @click="search"
          style="
            width: 67px;
            height: 38px;
            background: #126bff;
            border-radius: 0px 6px 6px 0px;
            opacity: 1;
            color: #ffffff;
            border: none;
          "
        >
          查询
        </button>
      </div>
      <div class="searchResult">
        <p
          v-for="item in searchResult"
          @click="detail(item)"
          :key="item.id"
          style="height: 25px; line-height: 25px"
        >
          {{ item.name }}
        </p>
      </div>
    </div>
    <!-- <button @click="confirm">确认经纬度</button> -->
  </div>
</template>
<script>
import AMapLoader from "@amap/amap-jsapi-loader";
window._AMapSecurityConfig = {
  securityJsCode: "e91fb6f5602f0b88ddfacbc77dc4dfd8", // '「申请的安全密钥」',
};
export default {
  name: "APP",
  components: {},
  data() {
    return {
      map: null,
      // 标记点
      marker: "",
      // 位置信息
      form: {
        lng: "",
        lat: "",
        // address: "",
        // //地区编码
        // adcode: "",
      },
      searchAddress: "",
      auto: null,
      autoOptions: {
        input: "search-input", //绑定的搜索关键字的input标签ID，用这个注册
      },
      placeSearch: null,
      searchResult: [], // 搜索结果
    };
  },
  methods: {
    init() {
      // console.log("111");
    },
    async initAMap() {
      await AMapLoader.load({
        key: "a6df9ff1ca402174e05fae513d277dda", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
          "AMap.Scale",
          "AMap.ToolBar",
          "AMap.ControlBar",
          "AMap.Geocoder",
          "AMap.Marker",
          "AMap.CitySearch",
          "AMap.Geolocation",
          "AMap.AutoComplete",
          "AMap.InfoWindow",
          "AMap.PlaceSearch",
        ], // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      })
        .then((AMap) => {
          let fence = null; // 初始化打卡范围地点
          //初始化地图 获取到作为地图容器的DOM元素，创建地图实例
          this.map = new AMap.Map("amapcontainer", {
            //设置地图容器id
            resizeEnable: true,
            zoom: 11, // 地图显示的缩放级别 初始化地图级别
            viewMode: "3D", // 使用3D视图
            zoomEnable: true, // 地图是否可缩放，默认值为true
            dragEnable: true, // 地图是否可通过鼠标拖拽平移，默认为true
            doubleClickZoom: true, // 地图是否可通过双击鼠标放大地图，默认为true
            center: [116.708982, 39.510429], // 初始化中心点坐标 廊坊 // mapStyle: "amap://styles/darkblue", // 设置颜色底层
          });

          // 在地图上添加搜索框
          this.auto = new AMap.AutoComplete(this.autoOptions);
          this.auto.search(this.searchAddress, function (status, result) {
            console.log(status);
            console.log(result);
          });
          // 构造地点查询类
          this.placeSearch = new AMap.PlaceSearch({
            map: this.map,
          });
          // 监听搜索框的选中事件
          this.auto.on("select", () => {
            // console.log(e);
          }),
            //点击获取经纬度;
            this.map.on("click", (e) => {
              // this.map.zoom = 20;
              // console.log(this.marker);
              // 获取经纬度
              // console.log(e);
              this.form.lng = e.lnglat.lng;
              this.form.lat = e.lnglat.lat;
              // console.log(this.form);
              this.$emit("getLocation", this.form);
              // 根据经纬度获取星系地址
              var geocoder = new AMap.Geocoder({
                city: "010", // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
              });
              geocoder.getAddress(this.form, function (status, result) {
                // console.log();
                if (status === "complete" && result.info === "OK") {
                  // console.log(result.regeocode.formattedAddress); //详细地址
                  // result为对应的地理位置详细信息
                }
              });
              // 清除点
              this.removeMarker();
              // 标记点
              this.map.setFitView();
              // this.marker = new window.AMap.Marker({});/
              this.marker = new window.AMap.Marker({
                map: this.map,
                position: [e.lnglat.lng, e.lnglat.lat],
              });
              if (fence != null) {
                fence.setMap(null);
              }
              fence = new AMap.Circle({
                center: [e.lnglat.lng, e.lnglat.lat],
                radius: 200,
                strokeColor: "#126BFF",
                strokeOpacity: 0.5,
                strokeWeight: 1,
                fillColor: "#126BFF",
                fillOpacity: 0.2,
              });

              fence.setMap(this.map);
              this.map.setFitView();
              this.map.add(this.marker);
            });

          // ==
        })
        .catch(() => {
          // console.log(e);
        });
    },
    // 关键字查询
    search() {
      var that = this;
      this.searchResult = [];
      if (this.searchAddress == "") {
        this.initAMap();
      } else {
        this.removeMarker();
        var placeSearch = new window.AMap.PlaceSearch({
          // city 指定搜索所在城市，支持传入格式有：城市名、citycode和adcode
          city: "廊坊市",
          citylimit: true,
        });
        placeSearch.search(that.searchAddress, function (status, result) {
          // 查询成功时，result即对应匹配的POI信息
          // console.log(result);
          // console.log(status);
          var pois = result.poiList.pois;
          for (var i = 0; i < pois.length; i++) {
            var poi = pois[i];
            // console.log(poi);
            that.setMapMarker(poi);
            that.searchResult.push(poi);
          }
          // map.setFitView();
        });
      }
      // console.log(this.searchResult);
    },
    // 标记点
    setMapMarker(val) {
      // console.log(val.location);
      // 自动适应显示想显示的范围区域
      this.map.setFitView();
      // this.marker = new window.AMap.Marker({});/
      this.marker = new window.AMap.Marker({
        map: this.map,
        position: val.location,
        title: val.name,
      });

      this.map.setFitView();
      this.map.add(this.marker);
    },
    // 清除点
    removeMarker() {
      if (this.marker) {
        this.map.remove(this.marker);
      }
    },
    //详情
    detail(e) {
      let fence = null;
      this.map = new window.AMap.Map("amapcontainer", {
        zoom: 18,
        center: [e.location.lng, e.location.lat],
      });
      this.form.lng = e.location.lng;
      this.form.lat = e.location.lat;
      this.$emit("getLocation", this.form);
      // console.log(this.form);
      // console.log(e.location.lng, e.location.lat);
      this.marker = new window.AMap.Marker({
        position: [e.location.lng, e.location.lat],
        map: this.map,
        title: e.name,
      });
      if (fence != null) {
        fence.setMap(null);
      }
      fence = new window.AMap.Circle({
        center: [e.location.lng, e.location.lat],
        radius: 200,
        strokeColor: "#126BFF",
        strokeOpacity: 0.5,
        strokeWeight: 1,
        fillColor: "#126BFF",
        fillOpacity: 0.2,
      });

      fence.setMap(this.map);
      this.searchResult = [];
      this.map.add(this.marker);
    },
    // confirm() {
    //   console.log(this.form);
    //   this.$emit("getLocation", this.form);
    // },
    handleClick() {
      // console.log(1111111111);
    },
  },
  created() {
    // console.log("11111");
  },
  mounted() {
    // DOM初始化完成进行地图初始化
    this.initAMap();
    this.$parent.$on("init", this.handleClick);
  },
  destroyed() {
    // console.log(12222);
  },
};
</script>
<style lang="scss" scoped>
.search {
  // border: 1px red solid;
  position: absolute;
  top: 100px;
  left: 30px;
  // height: 100px;
}
#search-input .el-input__inner {
  height: 40px !important;
}
// /deep/#search-input /deep/.el-input__inner {
//   height: 40px !important;
// }
.searchResult {
  width: 300px;
  height: 200px;
  z-index: 99;
  overflow-y: auto;
}
.searchResult p {
  background: white;
  cursor: pointer;
}
</style>
